//
//  LMHeartButton.m
//  LM
//
//  Created by Kien Tran on 1/23/13.
//  Copyright (c) 2013 Kien Tran. All rights reserved.
//

#import "LMHeartButton.h"
#import "LMConstant.h"
@implementation LMHeartButton
@synthesize valuePercent = _valuePercent;

- (id) init {
    self = [super init];
    if (self) {
        self.valuePercent = 0.0f;
    }
    
    return self;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void) setValuePercent:(CGFloat)valuePercent {
    
    _valuePercent = valuePercent >= 100.0f ? 100.0f : valuePercent;
    
    [self setTitle:[NSString stringWithFormat:@"%.0f%%", _valuePercent] forState:UIControlStateNormal];
    [self setTintColor:[UIColor blackColor]];
    
       
    UIImage *heartIcon = [self drawHearIconWithPercentValue:_valuePercent];
    //Set result image
    [self setBackgroundImage:heartIcon forState:UIControlStateNormal];
    CGRect newFrame = self.frame;
    newFrame.size = heartIcon.size;
    self.frame = newFrame;

}

- (UIImage *) drawHearIconWithPercentValue:(CGFloat) percent {
    UIImage *heartImage = [UIImage imageNamed:kIMAGE_ICON_HEAR];
    
    //Create result bitmap
    UIGraphicsBeginImageContextWithOptions(heartImage.size, NO, [UIScreen mainScreen].scale);
    
    //Crop image
    CGFloat y = (100.0f - percent) * heartImage.size.height / 100.0f;
    CGFloat height = heartImage.size.height - y;
    CGRect cropRect = CGRectMake(0, y, heartImage.size.width, height);
    CGImageRef imageRef = CGImageCreateWithImageInRect([heartImage CGImage], cropRect);
    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    
    //Draw cropped Image
    [cropped drawInRect:cropRect];
    CGImageRelease(imageRef);
    
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();  // UIImage returned.
    //End draw image
    UIGraphicsEndImageContext();

    return resultImage;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
